package bud.taskmanager.user;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import bud.taskmanager.user.dto.User;
import bud.taskmanager.user.service.UserService;

@Controller
public class UserController {

	@Autowired
	private UserService userService;

	@RequestMapping(value = "/users", method = RequestMethod.GET)
	public String list(ModelMap model) {
		model.addAttribute("users", userService.findAllUsers());
		return "user/list";
	}

	@RequestMapping(value = "/users/new", method = RequestMethod.GET)
	public String form(ModelMap model) {
		model.addAttribute("user", new User());
		return "user/form";
	}

	@RequestMapping(value = "/users/new", method = RequestMethod.POST)
	public String formSubmit(@ModelAttribute("user") @Valid User user,
			BindingResult result) {
		/*
		 * if (bindingResult.hasErrors()) { return new
		 * ModelAndView("user/form").getView(); }
		 * RedirectView rv = new RedirectView("users", false); return rv;
		 */
		if (result.hasErrors()) {
			return "user/form";
		}
		
		System.out.println("=======" + user.getId());

		if (user.getId() > 0)
			userService.updateUser(user);
		else
			userService.createUser(user);

		return "redirect:";
	}
	
	@RequestMapping(value = "/users/delete/{id}")
	public String delete(@PathVariable("id") int id) {
		userService.deleteUser(id);		
		return "redirect:..";
	}

	@RequestMapping(value = "/users/edit/{id}", method = RequestMethod.GET)
	public String edit(@PathVariable("id") int id, ModelMap model) {
		model.addAttribute("user", userService.findUser(id));
		return "user/form";
	}
}
